/*
 * @Author: 码农 2646995216@qq.com
 * @Date: 2025-03-05 22:37:01
 * @LastEditors: 码农 2646995216@qq.com
 * @LastEditTime: 2025-03-07 12:36:55
 * @FilePath: /pthread/text.cc
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
#include<iostream>
#include"BlockQueue.hpp"
#include<pthread.h>
#include<ctime>
#include<unistd.h>
#include"Task.hpp"

//消费者
void* conmuser(void* args)
{
    BlockQueue<Task>* td=static_cast<BlockQueue<Task>*>(args);
    while(true)
    {
        Task t=td->pop();
    
        t.run();
        cout<<"conmuser get a task:"<<t.GetResult()<<endl;
        sleep(1);
    }
}

//生产者
void* producer(void* args)
{
    int len=oper.size();
    srand(time(nullptr));
    BlockQueue<Task>* td=static_cast<BlockQueue<Task>*>(args);
    while(true)
    {
        int data1=rand()%5;
        usleep(100);
        int data2=rand()%10;
        char op=oper[rand()%len];

        Task t(data1,data2,op);

        td->push(t);
        cout<<"producer a task:"<<t.GetTask()<<endl;
        sleep(1);
    }
    
}

int main()
{
    BlockQueue<Task>* q=new BlockQueue<Task>;//创建队列
    pthread_t c,p;//定义生产者和消费者

    pthread_create(&c,nullptr,producer,(void*)q);//创建生产者的线程
    pthread_create(&c,nullptr,conmuser,(void*)q);//创建消费者的线程
 
    //回收线程
    pthread_join(c,nullptr);
    pthread_join(p,nullptr);
    
    //销毁队列
    delete q;

    return 0;
}



/*
void* conmuser(void* args)
{
    BlockQueue<Task>* td=static_cast<BlockQueue<Task>*>(args);
    while(true)
    {
        Task t=td->pop();
    
        t.run();
        cout<<"conmuser get a task:"<<t.GetResult()<<endl;
        sleep(1);
    }

}

void* producer(void* args)
{
    int len=oper.size();
    srand(time(nullptr));
    BlockQueue<Task>* td=static_cast<BlockQueue<Task>*>(args);
    while(true)
    {
        int data1=rand()%5;
        usleep(100);
        int data2=rand()%10;
        char op=oper[rand()%len];

        Task t(data1,data2,op);

        td->push(t);
        cout<<"producer a task:"<<t.GetTask()<<endl;
    }
    
}

int main()
{
    BlockQueue<Task>* q=new BlockQueue<Task>;
    pthread_t c[3],p[5];

    for(int i=0;i<3;i++)
    {
        pthread_create(c+i,nullptr,conmuser,(void*)q);
    }

    for(int j=0;j<5;j++)
    {
        pthread_create(p+j,nullptr,producer,(void*)q);
    }

    for(auto a:c)
    {
        pthread_join(a,nullptr);
    }

    for(auto b:p)
    {
        pthread_join(b,nullptr);
    }

    delete q;

    return 0;
}
    */
